<template>
  <view>
    <view class="color-bg-fff margin-10 padding-15 border-radius-10 shadow">
      <view class="font-16 color-333 font-weight margin-bottom-10">{{ info.className }}</view>
      <view class="flex-between font-14 color-666 margin-bottom-5">
        <view>可开票金额：<text class="color-main font-weight">￥{{ info.amount }}</text></view>
        <view>下单日期：{{ info.orderDate }}</view>
      </view>
      <view class="font-12 color-999">订单号：{{ info.orderNo }}</view>
    </view>
    <view class="color-bg-fff margin-10 padding-15 border-radius-10 shadow">
      <u-form
        ref="uForm"
        :model="form"
        :rules="rules"
        label-width="120"
        label-align="left"
      >
        <u-form-item label="发票抬头" prop="headerName" @click="openInvoiceHeaderModal">
          <u-input 
            v-model="form.headerName" 
            placeholder="请选择发票抬头" 
            border="none" 
            readonly
            :customStyle="{backgroundColor: 'transparent', color: '#333'}"
            style="pointerEvents: none"
          ></u-input>
        </u-form-item>
        <u-line margin="10rpx 0"></u-line>
        
        <u-form-item label="班次名称" prop="className">
          <u-input 
            v-model="form.className" 
            placeholder="班次名称" 
            border="none" 
            disabled
            :customStyle="{backgroundColor: '#f5f5f5', color: '#666'}"
          ></u-input>
        </u-form-item>
        <u-line margin="10rpx 0"></u-line>
        
        <u-form-item label="开票金额" prop="invoiceAmount">
          <u-input 
            v-model="form.invoiceAmount" 
            placeholder="开票金额" 
            border="none" 
            disabled
            :customStyle="{backgroundColor: '#f5f5f5', color: '#666'}"
          ></u-input>
        </u-form-item>
        <u-line margin="10rpx 0"></u-line>
        
        <u-form-item>
          <u-button type="primary" shape="circle" @click="submitForm">提交申请</u-button>
        </u-form-item>
      </u-form>
    </view>
    
    <!-- 发票抬头选择弹窗 -->
    <yd-choose 
      :show="showInvoiceHeaderModal" 
      title="选择发票抬头" 
      :options="invoiceHeaderOptions" 
      :dictCode="form.headerId"
      @onClose="showInvoiceHeaderModal = false" 
      @select="onInvoiceHeaderSelect" 
    />

    <!-- 确认提交弹框 -->
    <u-popup :show="showConfirmModal" mode="center" border-radius="20" width="600rpx" @close="showConfirmModal = false">
      <view class="confirm-modal">
        <view class="modal-header text-center padding-20">
          <view class="modal-title font-18 font-weight color-333">确认提交</view>
        </view>
        
        <view class="modal-content padding-x-20 padding-bottom-20">
          <view class="warning-text color-666 font-14 line-height-1-5">
            <view class="margin-bottom-10">请确认以下信息无误：</view>
            
            <!-- 发票抬头信息 -->
            <view class="margin-bottom-10">
              <view class="margin-bottom-5 font-weight">发票抬头信息：</view>
              <view v-if="form.headerInfo">
                <!-- 个人抬头 -->
                <view v-if="form.headerInfo.headerType === 2" class="margin-left-10">
                  <view class="margin-bottom-3">• 类型：个人</view>
                  <view class="margin-bottom-3">• 姓名：{{ form.headerInfo.personalName }}</view>
                </view>
                <!-- 企业抬头 -->
                <view v-else class="margin-left-10">
                  <view class="margin-bottom-3">• 类型：企业</view>
                  <view class="margin-bottom-3">• 企业名称：{{ form.headerInfo.companyName }}</view>
                  <view class="margin-bottom-3">• 公司税号：{{ form.headerInfo.taxNumber || '未填写' }}</view>
                  <view class="margin-bottom-3">• 注册地址：{{ form.headerInfo.registeredAddress || '未填写' }}</view>
                  <view class="margin-bottom-3">• 注册电话：{{ form.headerInfo.registeredPhone || '未填写' }}</view>
                  <view class="margin-bottom-3">• 开户银行：{{ form.headerInfo.bankName || '未填写' }}</view>
                  <view class="margin-bottom-3">• 银行账号：{{ form.headerInfo.bankAccount || '未填写' }}</view>
                </view>
              </view>
              <view v-else class="margin-left-10 color-red">未选择发票抬头</view>
            </view>
            
            <view class="margin-bottom-5">• 班次名称：{{ form.className }}</view>
            <view class="margin-bottom-5">• 开票金额：￥{{ form.invoiceAmount }}</view>
            <view class="margin-top-15 color-orange font-weight">
              ⚠️ 提交后无法修改，无法撤回，请谨慎操作！
            </view>
          </view>
        </view>
        
        <view class="modal-footer padding-20">
          <view class="flex-between">
            <u-button 
              size="medium" 
              type="default" 
              @click="cancelSubmit"
              style="width: 45%;">
              取消
            </u-button>
            <u-button 
              size="medium" 
              color="#5BA2F9" 
              @click="confirmSubmit"
              style="width: 45%;">
              确认提交
            </u-button>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { getClassDetail } from '@/api/course/class'
import { addInvoice } from '@/api/course/invoice'
import { myInvoiceHeaderList } from '@/api/course/invoiceHeader'
import YdChoose from '@/components/yd-choose/yd-choose.vue'

export default {
  components: {
    YdChoose
  },
  data() {
    return {
      classId: null, // 班次ID
      showConfirmModal: false, // 确认弹框显示状态
      showInvoiceHeaderModal: false, // 发票抬头选择弹框显示状态
      invoiceHeaderOptions: [], // 发票抬头选项
      info: {
        className: '',
        amount: '',
        orderDate: '',
        orderNo: ''
      },
      form: {
        headerId: null,       // 发票抬头ID
        headerName: '',       // 发票抬头名称
        headerInfo: null,     // 完整的发票抬头信息
        classId: null,        // 班次ID
        className:'',        // 班次名称
        invoiceAmount: '',    // 开票金额
      },
      rules: {
        headerName: [
          { required: true, message: '请选择发票抬头', trigger: ['blur', 'change'] }
        ],
      }
    }
  },
  onLoad(options) {
    // 获取班次ID参数
    if (options.classId) {
      this.classId = options.classId
      this.loadUserData()
      this.loadClassDetail()
      this.getInvoiceHeaderList() // 页面初始化时加载发票抬头
    } else {
      uni.showToast({
        title: '班次ID不能为空',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 500)
    }
  },
  methods: {
    // 加载用户数据
    loadUserData() {
      // 不再需要加载用户数据，因为已经去掉了申请人信息字段
    },
    
    // 加载班次详情数据
    async loadClassDetail() {
      if (!this.classId) {
        uni.showToast({
          title: '班次ID不能为空',
          icon: 'none'
        })
        return
      }
      
      try {
        uni.showLoading({
          title: '加载中...'
        })
        
        const response = await getClassDetail(this.classId)
        
        if (response.code === 200 && response.data) {
          const classData = response.data
          
          // 更新班次信息用于开票
          this.info = {
            className: classData.className || '班级名称',
            amount: classData.currentPrice || 0,
            orderDate: classData.enrollDate || classData.createTime || new Date().toISOString().split('T')[0],
            orderNo: classData.orderNo || `ORD${this.classId}${Date.now()}`
          }
          
          // 填充表单中的班次ID和开票金额
          this.form.classId = classData.id
          this.form.className = classData.className
          this.form.invoiceAmount = classData.currentPrice || 0
          
        } else {
          uni.showToast({
            title: response.msg || '获取班次详情失败',
            icon: 'none'
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 500)
        }
      } catch (error) {
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 500)
      } finally {
        uni.hideLoading()
      }
    },
    
    submitForm() {
      this.$refs.uForm.validate().then(() => {
        // 表单验证通过，显示确认弹框
        this.showConfirmModal = true
      }).catch((errors) => {
        uni.showToast({
          title: '请检查表单信息',
          icon: 'none'
        })
      });
    },
    
    // 取消提交
    cancelSubmit() {
      this.showConfirmModal = false
    },
    
    // 确认提交
    async confirmSubmit() {
        uni.showLoading({
          title: '提交中...'
        })
        
        // 构建提交数据
        const submitData = {
          classId: this.form.classId,
          headerId: this.form.headerId,
          invoiceAmount: this.form.invoiceAmount
        }
        
        const response = await addInvoice(submitData)
        if (response.code === 200) {
          uni.hideLoading()
          this.showConfirmModal = false
          
          uni.showToast({
            title: '申请提交成功',
            icon: 'success'
          })
          
          // 延迟跳转到开票记录页面
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages/work/invoice/record'
            })
          }, 500)
        } else {
          uni.hideLoading()
          uni.showToast({
            title: response.msg || '提交失败，请重试',
            icon: 'none'
          })
        }
    },
    
    // 获取发票抬头列表
    async getInvoiceHeaderList() {
      try {
        const response = await myInvoiceHeaderList({})
        const invoiceHeaderList = response.data || []
        
        // 转换为yd-choose组件需要的格式
        // dictCode 对应 headerId，dictLabel 对应显示文本
        this.invoiceHeaderOptions = invoiceHeaderList.map(item => ({
          dictCode: item.id, // 这里的 item.id 就是 headerId
          dictLabel: item.headerType === 1 ? item.companyName : item.personalName,
          // 保留其他字段用于可能的扩展
          header: item
        }))
      } catch (error) {
        console.error('获取发票抬头列表失败:', error)
        uni.showToast({
          title: '获取发票抬头列表失败',
          icon: 'none'
        })
      }
    },
    
    // 处理发票抬头选择
    onInvoiceHeaderSelect(selectedItem) {
      this.form.headerId = selectedItem.dictCode // 将 headerId 写入表单
      this.form.headerName = selectedItem.dictLabel // 将 headerName 写入表单
      this.form.headerInfo = selectedItem.header // 保存完整的发票抬头信息
      this.showInvoiceHeaderModal = false
    },
    
    
    // 打开发票抬头选择弹框
    openInvoiceHeaderModal() {
      // 如果发票抬头数据为空，则重新加载
      if (this.invoiceHeaderOptions.length === 0) {
        this.getInvoiceHeaderList().then(() => {
          this.showInvoiceHeaderModal = true
        }).catch(() => {
          uni.showToast({
            title: '加载数据失败',
            icon: 'none'
          })
        })
      } else {
        // 数据已存在，直接打开弹框
        this.showInvoiceHeaderModal = true
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.bottom{
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  padding: 30rpx 20rpx 40rpx 20rpx;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

.confirm-modal {
  background: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  
  .modal-header {
    border-bottom: 1px solid #f0f0f0;
    
    .modal-title {
      color: #333;
    }
  }
  
  .modal-content {
    .warning-text {
      line-height: 1.5;
      
      .color-orange {
        color: #ff6600;
      }
      
      .margin-left-10 {
        margin-left: 20rpx;
      }
      
      .margin-bottom-3 {
        margin-bottom: 6rpx;
      }
      
      .color-red {
        color: #ff4757;
      }
    }
  }
  
  .modal-footer {
    border-top: 1px solid #f0f0f0;
  }
}

</style>